#include <string.h>
#include <time.h>
#include <assert.h>
#include <setjmp.h>
#include "log.h"


int allocate_handled = 0;
jmp_buf allocate_failed;
static char logpath[104]={0};
static int logmode = 0;
static int loglevel = 0;
 
int gettime(char *out,int fmt)
{
  if (out == NULL) return -1;
  
  time_t t;
  struct tm *tp;
  t = time(NULL);

  tp = localtime(&t);
  if (fmt == 0)
     sprintf(out,"%2.2d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d",tp->tm_year+1900,tp->tm_mon+1,
              tp->tm_mday,tp->tm_hour,tp->tm_min,tp->tm_sec);

  else if (fmt == 1)
     sprintf(out,"%2.2d-%2.2d-%2.2d",tp->tm_year+1900,tp->tm_mon+1,tp->tm_mday);
  else
     sprintf(out,"%2.2d:%2.2d:%2.2d",tp->tm_hour,tp->tm_min,tp->tm_sec);
 
  return 0;
}

void initlog(int mode,int level,char *path)
{
  logmode = mode;
  loglevel = level ;
  strcpy(logpath,path); 
}

void writelog(int level,char *fmt,...)
{
  
  if (level > loglevel) {
    return;
  }
 
  char buf[LOG_BUFF] = {0};
  char curtime[60]={0};
  va_list args;

  gettime(curtime,0);

  if (level == LOG_ERROR)
    sprintf(buf,"[%d-%u,%s,%d,%d,%s]:",getpid(),(unsigned int)pthread_self(),__FILE__,__LINE__,getpid(),curtime);
  else
    sprintf(buf,"[%d-%u,%s]:",getpid(),(unsigned int)pthread_self(),curtime);

  va_start(args,fmt);
  vsprintf(buf+strlen(buf),fmt,args);
  va_end(args);

  if (logmode){
    printf("%s\n",buf);
  }
  else{
    
    char logfile[60] = {0};
    char fulllogfile[200] = {0};
    gettime(logfile,1);
    sprintf(fulllogfile,"%s/%s.log",logpath,logfile);
    FILE *fp = fopen(fulllogfile,"a+");
    if (fp){
      fprintf(fp,"%s\n",buf);
      fclose(fp);
    }
  }
}
